﻿(function ($) {
    var defaultOpt = {
        inputHander: '',
        openHander: '',
        onSelect: $.noop
    };
    $.emojiSelect = function (options) {
        var opts = $.extend(true, {}, defaultOpt, options);
        var uniqueID = "emojiSelect-" + new Date().getTime() + "-" + parseInt(Math.random() * 1000);
        var $emojiSelectDiv = $("<div/>", {
            id: uniqueID,
            class: 'emoji-select',
            onselectstart: "return false",
            onselect: "document.selection.empty()",
            ondragstart: "return false"
        });
        $("body").append($emojiSelectDiv);

        var $header = $('<div class="emoji-select-hander">\
                            <span class="emoji-select-title">请选择表情</span>\
                            <span class="emoji-select-close">关闭</span>\
                         </div>')
        $header.appendTo($emojiSelectDiv);
        
        var $emojiUl = $('<ul/>', { class: 'emoji-select-ul' });
        $emojiUl.appendTo($emojiSelectDiv);

        initEmojiContent();

        //初始化内容
        function initEmojiContent() {
            var emojiArr = [];
            var totalEmojiContent = '😊😃😄😂😭😍😘😚😜😝😌😏😉😁😳😠😡😨😰😱😥😢😪😓😞😔😒😲😣😖😷😀😛😋😅😇😆😫😩😵😤😴😶👿👻💩' +
                '💛💚💙💜❤💔💘💝🌹👄👌👉👈👇👆☝✌👍👎👊✊✋👐🙌👏💪👂👃👀🙏💀👽👧👦👩👨👵👴👶👼👸👱👲👮👷💂👳💑💏👫' +
                '🎎🙇🚶🏃💃🙆🙅💁💆💇👯☀🌙🌟✨🔥⚡☁💨💦☔⛄🎵🎶💤👣❕❔❌⭕💢♨🌸🌺🌷🌻💐🌾🍃🍂🍁🍀🌴🌵🎍🎄🎃🎅🎁👑🔔' +
                '📣📢🎉🎏🎐⛺🍄🍭🍐🍍🍌🍒🍇🍆🍎🍅🍊🍓🍉🍺🍻☕🍵🍸🍧🍦🍡🍢🎂🍰🍶🍞🍔🍟🍛🍱🍘🍙🍣🍝🍜🍲🍚🍳🍴🏆💰🔫' +
                '💣🚬✂💉💊🌀👾🐷🐱🐶🐺🐭🐹🐮🐯🐰🐍🐴🐎🐑🐵🐒🐔🐤🐦🐧🐗🐨🐻🐛🐫🐸🐙🐠🐟🐬🐳🌊🐚💎💍🌂💄💅🎀👙👠👗' +
                '👜🎈💡🔑🔓🔒🎰💿📷🎥📺💻📱🚗🚕🚙🚓🚒🚑🚃🚌🚉🚄✈🚀🚲🚤⛵🎿🏄🏊⚽🏀🏈🎾⚾🎱⛳🎮🎨🎺🎷🎸🎤🎧🀄🛀🚽' +
                '🏠⛪🏪🏥🏨🏦🏧💈🚥🚧🏁📖📈🚺🚹';


            var regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;

            var mapItem = regStr.exec(totalEmojiContent);
            while (mapItem) {
                emojiArr.push(mapItem[0]);
                mapItem = regStr.exec(totalEmojiContent);
            }

            var appHtml = "";
            emojiArr.forEach(function (item) {
                appHtml += "<li><span class='emoji-item'>" + item + "</span></li>";
            });

            $emojiUl.html(appHtml);

            $emojiUl.on('click', 'li', function () {
                var text = $(this).find('span.emoji-item').text();

                if ($inputHander.length > 0) {
                    var pos = $inputHander.attr('pos') || '0';
                    pos = parseInt(pos);

                    var content = $inputHander.val();

                    var content1 = content.substr(0, pos);
                    var context2 = content.substr(pos);
                    content1 += text;
                    $inputHander.val(content1 + context2);
                    $inputHander.attr('pos',pos + 2);
                }

                opts.onSelect(text);
            });
        }

        $emojiSelectDiv.on('click', '.emoji-select-close', function () {
            hide();
            return false;
        })

        //自动记录光标位置
        var $inputHander = $(opts.inputHander);
        $inputHander.blur(function () {
            var pos = getCursortPosition(this);
            $(this).attr('pos', pos);
        });

        var $openHander = $(opts.openHander);
        $openHander.click(function () {
            show({ top: $(this).offset().top });
        });


        //获取 文本框光标位置
        function getCursortPosition(ctrl) {
            var CaretPos = 0;
            // IE Support
            if (document.selection) {
                ctrl.focus();
                var Sel = document.selection.createRange();
                Sel.moveStart('character', -ctrl.value.length);
                CaretPos = Sel.text.length;
            }
            // Firefox support
            else if (ctrl.selectionStart || ctrl.selectionStart == '0')
                CaretPos = ctrl.selectionStart;
            return (CaretPos);
        }

        function show(pos) {
            var top = pos.top;
            if (top !== undefined) {
                $emojiSelectDiv.css({ top: top, position: 'absolute'});
            }
            $emojiSelectDiv.slideDown(function () {
                $emojiSelectDiv.attr('open', 'open');
            });
        }

        function hide() {
            $emojiSelectDiv.removeAttr('open');
            $emojiSelectDiv.slideUp();
        }

        $(document).on('click', function (e) {
            if ($emojiSelectDiv.find(e.target).length <= 0) {
                if ($emojiSelectDiv.attr('open') == 'open') { 
                    hide();
                }
            }
        });

        return {
            show: show,
            hide:hide
        };
    }
})(jQuery);